package com.yunkai.plate_lpr;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class ImageUtil {

  private static int quality = 40;
  private static SimpleDateFormat aDateName = new SimpleDateFormat("yyyy_MM_dd/");
  public static String parent = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DETECTION/";
  public static void setQuality(int q){
    quality = q;
  }

  public static String saveImage(Context context, Bitmap bitmap) {
    Date now = new Date();
    Log.i("ImageUtil", "start to save img");

    String day = aDateName.format(now);
    String path = parent+day;
    File f = new File(path+"/", UUID.randomUUID().toString().replaceAll("-","") +".jpg");
    File fullpath = new File(path);
    if(!fullpath.exists()){
      fullpath.mkdirs();
    }
    Log.i("ImageUtil", "save image path"+path+"/"+ System.currentTimeMillis()+".jpg");
    try {
      FileOutputStream out = new FileOutputStream(f);
      bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
      out.flush();
      out.close();
      Log.i("ImageUtil", "save image success");
    } catch (IOException e) {
      Log.i("ImageUtil", "save img error");
      e.printStackTrace();
    }
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri uri = Uri.fromFile(f);
    intent.setData(uri);
    context.sendBroadcast(intent);
    return f.getAbsolutePath();
  }


  public static void deletePics(int days) {
    Log.i("ImageUtil", "删除3天内的图片");
    File parentpath = new File(parent);
    Date cur_date = new Date();
    if (parentpath.exists()) {
      for (File file : parentpath.listFiles()) {
        String directory_name = file.getName();
        Date file_date;
        try {
          file_date = aDateName.parse(directory_name+"/");
        } catch (ParseException e) {
          deleteDirector(file);
          break;
        }
        assert file_date != null;
        long diff = cur_date.getTime() - file_date.getTime();
        if (diff / (1000 * 60 * 60) > (24 * days)) {
          deleteDirector(file);
        }
      }
    }
  }


  private static void deleteDirector(File file){
    for (File filei : file.listFiles()) {
      filei.delete();
    }
    file.delete();
  }

}
